#!/usr/bin/python

"""
Licenced under GNU v2 and the 'I'm not going to help you kill people licence'. The latter overrules the former.
        
I'm not going to help you kill people licence v1:
The use of this software in any form for any purposes relating to any form of military activity or
research either directly or via subcontracts is strictly prohibited.
Any company or organisation affiliated with any military organisations either directly or through
subcontracts are strictly prohibited from using any part of this software.

GNU licence:        
rsdl is free software; you can redistribute it and/or modify it 
under the terms of the GNU General Public License as published by the Free Software Foundation; 
either version 2 of the License, or (at your option) any later version.

rsdl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
See the GNU General Public License for more details. You should have received a copy of 
the GNU General Public License along with File Hunter; if not, write to 
the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""


import sys, time, os, rsdl, optparse, getpass

# TODO - delete all tasks when done, or prevent from writing to disc

# Passed to download threads so they can give feedback info to the gui (including when they are finished)
class FeedbackMessageHandler:
    def __init__(self, parent, verbose):
        self.parent = parent
        self.verbose = verbose
    
    def setStatus(self, text):
    	if self.verbose:
	        print text
    
    def listUpdate(self):
    	if self.verbose:
    		if len(self.parent.tasks) == 1:
    			print "%s -\t%s%%\tspeed %s\t%s remaining" % (	str(self.parent.tasks[0].status),
    										str(self.parent.tasks[0].progress),
    										str(self.parent.tasks[0].currentSpeed),
    										str(self.parent.tasks[0].timeRemaining)
    			)
    		else:
			print "=============    RSDL Status    ============="
			for t in self.parent.tasks:
				path, filename = os.path.split(t.url)
				#print ".." + filename + " @ " + str(t.currentSpeed) + " KB/s - " + str(t.progress) + "%, " + str(t.timeRemaining) + " remain " + str(t.status)
				print "..%s\t%s\t@ %s\t%s%%\t%s remaining" % (	filename,
										str(t.status),
    										str(t.currentSpeed),
    										str(t.progress),
    										str(t.timeRemaining)
    			)

		#str( int( float(t.size) / 1048576.0 ) ) + " MB"
		#str(t.speed)
		#str(t.directLink)
		#str(t.status)



#print "Download files from rapidshare either individually or in batch\n"


#print "Examples:"
#print "   ./rapidtask.py --limit 50 --download http://rapidshare.com/files/14/file.rar"
#print "   Download single file at speed 50 KB/s\n"
#print "   ./rapidtask --batch localfile --pause 30"
#print "   Download all files listed in the file 'localfile',\n   pause for 30 seconds between files"
#print "Notes:"
#print "   The --mirrors option is used if you have manually selected the mirror on the"
#print "   rapidshare page (after selecting 'PREMIUM')."




def main():
	# Find user directory
	if sys.platform=="win32":
		homePath = os.path.join( os.environ.get("USERPROFILE"), "Application Data" )
	else:
		homePath = os.environ.get("HOME")

	usage = "usage: %prog [options] COMMAND\n\nList of commands:\n\ndownload    download single file\nbatch       download urls listed in text file\ngetcookie   download rapidshare cookie file"
	parser = optparse.OptionParser(usage=usage)

	parser.add_option("-s", "--speed", action="store", dest="speed", default=None, help="set download speed limit in KB/s", metavar="KBPS")
	parser.add_option("-n", "--destination", action="store", dest="destination", default=os.getcwd(), help="set download destination pat")
	parser.add_option("-t", "--threads", action="store", dest="threads", type="int", default=1, help="set number of concurrent downloads")
	#parser.add_option("-p", "--pause", action="store", dest="pause", help="set pause between downloading files in seconds")
	
	parser.add_option("-d", "--direct", action="store_true", dest="direct", default=False, help="use direct file links on mirrors")
	parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="do not display any output")
	#parser.add_option("-c", "--cookie-file", action="store", dest="cookie_file", help="path to cookie file")
	
	
	options, args = parser.parse_args()
	
	if len(args) < 1:
		parser.error("no command was specified")
	
	# Select user command
	if len(args) == 2 and args[-2] == "download":
		# Download a single file
		if rsdl.checkCookie():
			tasks = rsdl.TaskList()
			url = args[-1]	
			tasks.feedback = FeedbackMessageHandler(tasks, options.verbose)
			speed = None
			if options.speed:
				speed = float(options.speed)
			task = rsdl.Task(url, options.direct, speed, options.destination)
			task.status = "Queued"
			tasks.addTask(task)
			tasks.downloadTasks(1)
		else:
			parser.error("Cookie not found, use the getcookie command")
	
	elif len(args) == 2 and args[-2] == "batch":
		# Download a batch of files
		filename = args[-1]
		if rsdl.checkCookie():
			tasks = rsdl.TaskList()
			tasks.feedback = FeedbackMessageHandler(tasks, options.verbose)
			if options.verbose:
				print "fn", filename
			f = open(filename)
			lines = f.read().split("\n")
			f.close()
			
			for url in lines:
				if options.verbose:
					print "'" + url + "'"
				if len(url) > 0:
					speed = None
					if options.speed:
						speed = float(options.speed)
					task = rsdl.Task(url, options.direct, speed, options.destination)
					task.status = "Queued"
					tasks.addTask(task)
			
			tasks.downloadTasks(options.threads)	
		else:
			parser.error("Cookie not found, use the getcookie command")
			
	
	elif len(args) == 1 and args[-1] == "getcookie":
		# Download rapidshare cookie
		username = raw_input("Username: ")
		password = getpass.getpass()
		rsdl.downloadCookie(username, password)
		if rsdl.checkCookie():
			print "Success"
		else:
			print "Failed"

	else:
		parser.print_help()

	




if __name__ == "__main__":
	main()

